const express = require("express")
const path = require('path')
const app = express()
const fs = require("fs")
const multer  = require('multer')
const mysql = require("mysql")
const artTemplate = require('art-template')
const expressTemplate = require("express-art-template")

app.set('views',__dirname+'/view/')
app.engine('html',expressTemplate);
app.set('view engine','html')
app.use(express.static("bao"));
app.use(express.static(__dirname));



var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root', //连接名
   password: '123456',
    database: 'root'//数据库
});

// 启动mysql,并连接到数据库
connection.connect();



app.get('/',(req,res)=>{
   
    let sql = `select * from article`
    
connection.query(sql, (err, result, fields) => {
    res.render('index.html',{result})
})
    
})

// 设置上传的目录
var upload = multer({ dest: 'uploads/' })

// 处理文件上传
app.post('/upload',upload.single('photo'),(req,res)=>{
   
    let {originalname,filename,destination} = req.file;
    let {title,author,content,time} = req.body;
    console.log(req.file);
    console.log(req.body);
    let ext = originalname.substring( originalname.indexOf('.') ); // .png
    // 把上传成功后的文件进行重命名
    let oldPath = path.join( __dirname,destination,filename);
    let newPath = path.join( __dirname,destination,filename) + ext;
    fs.renameSync(oldPath,newPath)
    
    let sql = `insert into article(title,img,author,content,time) values ("${title}","${destination}${filename}.png","${author}","${content}","${time}")`
    connection.query(sql, (err, result, fields) => {
        console.log(result);
        res.redirect('/')
    })
})


app.get('/delete',(req,res)=>{
	//req.query用来接收get请求,req.body用来接收post请求
    let {id} = req.query;
    let sql = `delete from article where id=${id} `
connection.query(sql, (err, result, fields) => {
    res.redirect('/')
})

})


app.get('/zhen',(req,res)=>{

    res.render('zhen.html')

}) 

app.get('/cha',(req,res)=>{
    let {chaid} = req.query;
    let sql = `select * from article where id=${chaid} `

connection.query(sql, (err, result, fields) => {
    res.render('cha.html',{result})
})
})


app.get('/gai',(req,res)=>{
    
    let {gaiid} = req.query;
    let sql = `select * from article where id = ${gaiid}`
connection.query(sql, (err, result, fields) => {
    res.render('gai.html',{result})
})
})


app.get('/gaichen',(req,res)=>{
    
    let {title,img,author,content,status,time,gaiid} = req.query;
    let sql = `update article set title='${title}',img='${img}',author='${author}',content='${content}',status='${status}',time='${time}' where id= ${gaiid};`
connection.query(sql, (err, result, fields) => {
    res.redirect('/')
})
})



app.listen(4000,()=>{
    console.log("好了");
})
